package com.wrupple.muba.desktop.client.bootstrap.state.impl;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.MetaElement;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.wrupple.muba.common.client.JSOHelper;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.desktop.client.bootstrap.state.ReadDesktopMetadata;
import com.wrupple.muba.desktop.client.module.DesktopModuleController;
import com.wrupple.muba.desktop.domain.DesktopLoadingStateHolder;

public class ReadDesktopMetadataImpl implements ReadDesktopMetadata {

	@Inject
	public ReadDesktopMetadataImpl() {
		super();
	}

	@Override
	public void start(DesktopLoadingStateHolder parameter, StateTransition<DesktopLoadingStateHolder> onDone,EventBus eventBus) {
		
		NodeList<Element> metaTags = Document.get().getElementsByTagName("meta");
		
		MetaElement meta;
		String metaTagName;
		String metaContent;
		JavaScriptObject applicationHierarchy =null;
		JavaScriptObject userData = null;
		for(int i = 0 ; i < metaTags.getLength() ; i++){
			meta = metaTags.getItem(i).cast();
			metaTagName = meta.getName();
			if(DesktopModuleController.APPLICATION_HIERARCHY.equals(metaTagName)){
				metaContent=meta.getContent();
				applicationHierarchy = JSOHelper.eval(metaContent);
			}
			if(DesktopModuleController.USER_PARAMETER.equals(metaTagName)){
				metaContent=meta.getContent();
				userData = JSOHelper.eval(metaContent);
			}
		}
		
		parameter.setUserData(userData);
		parameter.setApplicationHierarchy(applicationHierarchy);
		
		
		onDone.setResultAndFinish(parameter);
	}
	
	

}
